/*
 * @Author: funlee
 * @Email: i@funlee.cn
 * @Date: 2018-06-22 10:46:56
 * @Description: 自定义形状 
 */
import React, { Component } from 'react';
import G6 from '@antv/g6';

export default class App extends Component {
  constructor(props) {
    super(props);
    G6.track(false)
    this.state = {
      chart: null
    }
  }
  componentDidMount() {
    const data = {
      nodes: [{
        id: 'node1',
        x: 50,
        y: 50,
        shape: 'rect'
      }, {
        id: 'node2',
        x: 100,
        y: 200,
        shape: 'custom'
      }]
    };

    G6.registerNode('rect', {
      draw(item) {
        const group = item.getGraphicGroup();
        this.drawText(item);
        return group.addShape('rect', {
          attrs: {
            x: 100,
            y: 100,
            width: 100,
            height: 100,
            stroke: 'red'
          }
        });
      },
      drawText(item) {
        const group = item.getGraphicGroup();
        const text = this.getText();
        group.addShape('text', {
          attrs: {
            x: 100,
            y: 100,
            fill: '#333',
            text
          }
        });
      },
      getText() {
        return '我是一个节点 rect';
      }
    });

    G6.registerNode('custom', {
      getText() {
        return '我是一个自定义节点，\n继承于 rect';
      }
    }, 'rect');

    const graph = new G6.Graph({
      container: 'mountNode',  // 容器ID
      width: 500,       // 画布宽
      height: 500,      // 画布高
    });

    this.setState({
      chart: graph
    })

    graph.read(data);
  }
  addRect() {
    const { chart } = this.state;
    const data = {
      'nodes': [{
        'shape': 'rect',
        'id': 'rectNode'
      }]
    }

    G6.registerNode('rect', {
      afterDraw(item) {
        const group = item.getGraphicGroup();
        return group.addShape('rect', {
          attrs: {
            x: 100,
            y: 100,
            width: 100,
            height: 100,
            stroke: 'red'
          }
        })
      }
    })

    chart.read(data)
  }
  addText() {
    const { chart } = this.state;
    const data = {
      'nodes': [{
        'shape': 'text',
        'id': 'textNode'
      }]
    }

    G6.registerNode('text', {
      draw(item) {
        const group = item.getGraphicGroup();
        group.addShape('text', {
          attrs: {
            x: 300,
            y: 500,
            fill: '#333',
            text: '自定义节点'
          }
        })
      }
    })

    chart.read(data)
  }
  render() {
    return (
      <div className="chart">
        <div className="btns">
          <button onClick={this.addRect.bind(this)}>add rect</button>
          <button onClick={this.addText.bind(this)}>add text</button>
        </div>
        <div id="mountNode">

        </div>
      </div>
    )
  }
}
